class SelectFile < ActiveRecord::Base
  attr_accessible :file, :server
  
  has_attached_file :xmlFile1
  has_attached_file :xmlFile2
  
  has_many :program_information_table, :dependent => :delete_all
  has_many :program_location_table, :dependent => :delete_all
  has_many :service_information_table, :dependent => :delete_all
  has_many :group_information_table, :dependent => :delete_all
  
  
  require 'xmlsimple'
  require 'nokogiri'
  require 'csv'
  require 'libxml'
  
  require 'xml/libxml'

  def self.loadXML(params)
    if(params[:defaultChannels] == "1")
      loadDefaultChannels()
    end
    if(params[:redbee] == "1")
      loadRedBeeinfo()
    end
    if(params[:axels] == "1")
      loadAxelSinfo()
    end
  end
  
  
  def self.loadDefaultChannels
    DefaultChannel.delete_all
    file = File.join(Rails.root,"public",'channelList','channel_list.csv')
    CSV.foreach(file) do |row|
      DefaultChannel.create(:name=>row[0], :language=>row[1])
    end
    
  end
 
  def self.insertRedBeeFile(file)
    if(SelectFile.where(:file=>file).first==nil)
      selectFile = SelectFile.create(:file=>file, :server=>'RedBee')
      id = selectFile.id
    else
      id = SelectFile.where(:file=>file).first.id
    end
  end
  def insertSIT(id)
    if(ServiceInformationTable.where(:select_file_id=>id).first==nil)
      sitCreated = ServiceInformationTable.create(:select_file_id=>id)
    else
      sitCreated = ServiceInformationTable.where(:select_file_id=>id).first
    end
  end
  def insertGIT(id)
    if(GroupInformationTable.where(:select_file_id=>id).first==nil)
      gitCreated = GroupInformationTable.create(:select_file_id=>id)
    else
      gitCreated = GroupInformationTable.where(:select_file_id=>id).first
    end
  end
  def insertPIT (id)
    if(ProgramInformationTable.where(:select_file_id=>id).first==nil)
      pitCreated = ProgramInformationTable.create(:select_file_id=>id)
    else
      pitCreated = ProgramInformationTable.where(:select_file_id=>id).first
    end
  end
  def insertPLT(id)
    if(ProgramLocationTable.where(:select_file_id=>id).first==nil)
      pltCreated = ProgramLocationTable.create(:select_file_id=>id)
    else
      pltCreated = ProgramLocationTable.where(:select_file_id=>id).first
    end
  end
  def insertProgramInformation(id,tableid)
    ProgramInformation.create(:crid=>id, :program_information_table_id=>tableid)
  end
  
  def insertServiceInformation(id,name,tableid)
    ServiceInformation.create(:serviceId=>id,  :name=>name, :service_information_table_id=>tableid)
  end
  def insertTitle(programInformationId, language, type, text)
     Title.create(:program_information_id=>programInformationId, :language=>language, :type_title=>type, :text=>text)
  end
  def insertKeyword(programInformationId, language, type, text)
     Keywordprogram.create(:program_information_id=>programInformationId, :language=>language, :type_keyword=>type,  :text=>text)
  end
  def insertSynopsis(programInformationId, language, length, text)
    Synopsis.create(:program_information_id=>programInformationId,  :language=>language, :length=>length,  :text=>text)
  end
  
  def insertEpisodeOf(programInformationId, type, index, crid)
    EpisodeOf.create(:program_information_id => programInformationId, :xsiType => type,  :index => index,  :crid => crid)
  end
  
  def insertMemberOf(programInformationId, type, index, crid)
    MemberOf.create(:program_information_id => programInformationId, :xsiType => type, :index => index,  :crid => crid)
  end
  
  def insertSchedule(serviceId, startschedule, endschedule, tableid)
    Schedule.create(:service_id=>serviceId,  :start=>startschedule,  :end=>endschedule, :program_location_table_id=>tableid)
  end
  
  def insertScheduleEvent(crid, start, duration, scheduleId)
    ScheduleEvent.create(:programCrid=>crid,  :startime=>start ,:duration=>duration, :schedule_id=>scheduleId)   
  end
  
  def insertAVAttributes(type, eventid, content, value)     
    if (value.start_with?("\n")) 
      value = ""
    end  
      Avattribute.create(:avtype=>type, :schedule_event_id=>eventid, :content=>content, :value=>value)
  end
  
  def insertGroupInformation(id, type, title, tableid)
    GroupInformation.create(:groupId=>id,  :group_type=>type,  :title=>title, :group_information_table_id=>tableid)
  end
  
  def self.loadRedBeeinfo()
    
    xmlDestination = File.join(Rails.root,"public",'XML','RedBee','20130213200307upc_.xml')
    insertRedBeeFile(xmlDestination)
    
    parser = XML::SaxParser.file(xmlDestination)
    parser.callbacks = SelectFile.new
    parser.parse
  end
  
  def self.loadAxelSinfo()
 
    axelSFolder = File.join(Rails.root,"public",'XML','AxelS')
    Dir.foreach(axelSFolder) do |item|
      next if item == '.' or item == '..'
      itemURL = File.join(axelSFolder, item)

      if(SelectFile.where(:file=>itemURL).first==nil)
        selectFile = SelectFile.create(:file=>itemURL, :server=>'AxelS.one')
        id = selectFile.id
      else
        id = SelectFile.where(:file=>itemURL).first.id
      end
      
      parser = XML::SaxParser.file(itemURL)
      parser.callbacks = SelectFile.new
      parser.parse
    
    end
    
  end
  
  include XML::SaxParser::Callbacks
  
  def on_start_element(element, attributes)
      if element == "ProgramInformationTable"
        insertPIT(SelectFile.last.id)
        set_pitFlag(true)
      end
      if element == "GroupInformationTable"
        insertGIT(SelectFile.last.id)
        set_gitFlag(true)
      end
      if element == "ProgramLocationTable"
        insertPLT(SelectFile.last.id)
        set_pltFlag(true)
      end
      if element == "ServiceInformationTable"
        insertSIT(SelectFile.last.id)
        set_sitFlag(true)
      end
      
      if(pitFlag)
        if element == "ProgramInformation"
          insertProgramInformation(attributes['programId'],ProgramInformationTable.last.id)
        end
        if element == "Title"
          setTitleFlag(true)
          set_lang(attributes['lang'])
          set_type(attributes['type'])
        end
        if element == "Synopsis"
          setSynopsisFlag(true)
          set_lang(attributes['lang'])
          set_length(attributes['length'])
        end
        if element == "Keyword"
          setKeywordFlag(true)
          set_lang(attributes['lang'])
          set_type(attributes['type'])
        end
        if element == "Language"
          setLangFlag(true)
        end
        if element == "EpisodeOf"
          insertEpisodeOf(ProgramInformation.last.id, attributes['type'], attributes['index'], attributes['crid'])
        end
        if element == "MemberOf"
          insertMemberOf(ProgramInformation.last.id, attributes['type'], attributes['index'], attributes['crid'])
        end
      end
      if(gitFlag)
        if element == "GroupInformation"
          set_crid(attributes['groupId'])
        end
        if element == "GroupType"
          set_type(attributes['value'])
        end
        if element == "Title"
          setTitleFlag(true)
        end
      end
      if(pltFlag)
        if element == "Schedule"
          insertSchedule(attributes['serviceIDRef'], attributes['start'],  attributes['end'], ProgramLocationTable.last.id)
        end
        if element == "Program"
          insertScheduleEvent(attributes['crid'], nil, nil, Schedule.last.id)
        end
        if element == "PublishedStartTime"
          setStartTimeFlag(true)
        end
        if element == "PublishedDuration"          
          setDurationFlag(true)
        end
        if element == "VideoAttributes"
          setVideoFlag(true)          
        end
        if element == "AspectRatio"
          setAspectRatioFlag(true)
        end
        if getVideoFlag && element == "Coding"
          setCodingFlag(true)
        end
        if element == "Scan"
          setScanFlag(true)
        end
        if element == "HorizontalSize"
          setHorizontalSizeFlag(true)
        end
        if element == "VerticalSize"
          setVerticalSizeFlag(true)
        end
        if element == "Color"
          setColorFlag(true)
        end
        if element == "FrameRate"
          setFrameRateFlag(true)
        end
        if element == "AudioAttributes"
          setAudioFlag(true)   
        end
        if getAudioFlag && element == "Coding"
          setAudioCodingFlag(true)
        end
        if element == "NumOfChannels"
          setNumChannelsFlag(true)
        end
        if element == "MixType"
          setMixTypeFlag(true)
        end
        if element == "AudioLanguage"
          setAudioLanguageFlag(true)
        end
      end
      if(sitFlag)
        if element == "ServiceInformation"
          set_id(attributes['serviceId'])
        end
        if element == "Name"
          setNameFlag(true)
        end
      end
  end
  
  def on_characters(chars)
    if(pitFlag)
      if(getLangFlag)
        setLangFlag(false)
        ProgramInformation.last.update_attribute(:language, chars)
      end
      if(getTitleFlag)
        setTitleFlag(false)
        insertTitle(ProgramInformation.last.id, get_lang, get_type, chars)
      end
      if(getSynopsisFlag)
        setSynopsisFlag(false)
        insertSynopsis(ProgramInformation.last.id, get_lang, get_length, chars)
      end
      if(getKeywordFlag)
        setKeywordFlag(false)
        insertKeyword(ProgramInformation.last.id, get_lang, get_type, chars)
      end
    end
    if(gitFlag)
      if(getTitleFlag)
        setTitleFlag(false)
        type = get_type
        insertGroupInformation(get_crid, type, chars, GroupInformationTable.last.id)
      end
    end
    if(pltFlag)
      if(getStartTimeFlag)
        setStartTimeFlag(false)
        ScheduleEvent.last.update_attribute(:startime, chars)
      end
      if(getDurationFlag)
        setDurationFlag(false)
        ScheduleEvent.last.update_attribute(:duration, chars)
      end
      if (getAspectRatioFlag)
        setAspectRatioFlag(false)
        insertAVAttributes('video', ScheduleEvent.last.id, 'AspectRatio', chars)
      end
      if (getCodingFlag)
        setCodingFlag(false)
        insertAVAttributes('video', ScheduleEvent.last.id, 'Coding', chars)
      end
      if (getCodingFlag)
        setCodingFlag(false)
        insertAVAttributes('video', ScheduleEvent.last.id, 'Coding', chars)
      end
      if (getScanFlag)
        setScanFlag(false)
        insertAVAttributes('video', ScheduleEvent.last.id, 'Scan', chars)
      end
      if (getHorizontalSizeFlag)
        setHorizontalSizeFlag(false)
        insertAVAttributes('video', ScheduleEvent.last.id, 'HorizontalSize', chars)
      end
      if (getVerticalSizeFlag)
        setVerticalSizeFlag(false)
        insertAVAttributes('video', ScheduleEvent.last.id, 'VerticalSize', chars)
      end
      if (getColorFlag)
        setColorFlag(false)
        insertAVAttributes('video', ScheduleEvent.last.id, 'Color', chars)
      end
      if (getFrameRateFlag)
        setFrameRateFlag(false)
        insertAVAttributes('video', ScheduleEvent.last.id, 'FrameRate', chars)
      end
      if (getAudioFlag)
        setAudioFlag(false)
        insertAVAttributes('audio', ScheduleEvent.last.id, 'Audio', chars)
      end
      if (getAudioCodingFlag)
        setAudioCodingFlag(false)
        insertAVAttributes('audio', ScheduleEvent.last.id, 'AudioCoding', chars)
      end
      if (getNumChannelsFlag)
        setNumChannelsFlag(false)
        insertAVAttributes('audio', ScheduleEvent.last.id, 'NumChannels', chars)
      end
      if (getMixTypeFlag)
        setMixTypeFlag(false)
        insertAVAttributes('audio', ScheduleEvent.last.id, 'MixType', chars)
      end
      if (getAudioLanguageFlag)
        setAudioLanguageFlag(false)
        insertAVAttributes('audio', ScheduleEvent.last.id, 'AudioLanguage', chars)
      end
    end
    if(sitFlag)
      if(getNameFlag)
        setNameFlag(false)
        insertServiceInformation(get_id,chars,ServiceInformationTable.last.id)
      end
    end
  end
  
  def on_end_element_ns (name, prefix, uri)
    if name == "ProgramInformationTable"
        set_pitFlag(false)
      end
      if name == "GroupInformationTable"
        set_gitFlag(false)
      end
      if name == "ProgramLocationTable"
        set_pltFlag(false)
      end
      if name == "ServiceInformationTable"
        set_sitFlag(false)
      end
  end
  
  def get_crid
    @crid
  end
  def set_crid(value)
    @crid = value
  end
  
  def get_duration
    @duration
  end
  def set_duration(value)
    @duration = value
  end
  
  def get_starttime
    @startime
  end
  def set_starttime(value)
    @startime = value
  end
  
  def get_length
    @length
  end
  def set_length(value)
    @length = value
  end
  
  def get_lang
    @lang
  end
  def set_lang(value)
    @lang = value
  end
  
  def get_type
    @type
  end
  
  def set_type(value)
    @type = value
  end
  
  def get_id
    @id
  end
  
  def set_id(value)
    @id = value
  end
  
  def get_name
    @name
  end
  
  def set_name(value)
    @name = value
  end
  
  def getNameFlag
    @nameFlag
  end
  
  def setNameFlag(value)
    @nameFlag = value
  end
  
  def getStartTimeFlag
    @startTimeFlag
  end
  def setStartTimeFlag(value)
    @startTimeFlag = value
  end
  
  def getDurationFlag
    @durationFlag
  end
  def setDurationFlag(value)
    @durationFlag = value
  end
  
  def getKeywordFlag
    @keywordFlag
  end
  def setKeywordFlag(value)
    @keywordFlag = value
  end
  
  def getSynopsisFlag
    @synopsisFlag
  end
  def setSynopsisFlag(value)
    @synopsisFlag = value
  end
  
  def getTitleFlag
    @titleFlag
  end
  def setTitleFlag(value)
    @titleFlag = value
  end
  
  def getLangFlag
    @langFlag
  end
  def setLangFlag(value)
    @langFlag = value
  end
  
  def pitFlag
    @pitFlag
  end
  
  def set_pitFlag(value)
    @pitFlag = value
  end
  
  def pltFlag
    @pltFlag
  end
  
  def set_pltFlag(value)
    @pltFlag = value
  end
  
  def gitFlag
    @gitFlag
  end
  
  def set_gitFlag(value)
    @gitFlag = value
  end
  
  def sitFlag
    @sitFlag
  end
  
  def set_sitFlag(value)
    @sitFlag = value
  end

  def selfresetFlags()
    setStartTimeFlag(false)
    setDurationFlag(false)
    setKeywordFlag(false)
    setSynopsisFlag(false)
    setTitleFlag(false)
    setLangFlag(false)
    set_pitFlag(false)
    set_pltFlag(false)
    set_gitFlag(false)
    set_sitFlag(false)
  end

  def setVideoFlag(value)
    @videoFlag = value
  end
  
  def getVideoFlag
    @videoFlag 
  end
  
  def setAspectRatioFlag(value)
    @aspectFlag = value
  end
  
  def getAspectRatioFlag
    @aspectFlag 
  end
  
  def setCodingFlag(value)
    @codingFlag = value
  end
  
  def getCodingFlag
    @codingFlag 
  end
  
  def setScanFlag(value)
    @scanFlag = value
  end
  
  def getScanFlag
    @scanFlag 
  end
  
  def setHorizontalSizeFlag(value)
    @horizontalSizeFlag = value
  end
  
  def getHorizontalSizeFlag
    @horizontalSizeFlag 
  end
  
  def setVerticalSizeFlag(value)
    @verticalSizeFlag = value
  end
  
  def getVerticalSizeFlag
    @verticalSizeFlag 
  end
  
  def setColorFlag(value)
    @colorFlag = value
  end
  
  def getColorFlag
    @colorFlag 
  end
  
  def setFrameRateFlag(value)
    @frameRateFlag = value
  end
  
  def getFrameRateFlag
    @frameRateFlag 
  end
  
  def setAudioFlag(value)
    @audioFlag = value
  end
  
  def getAudioFlag
    @audioFlag 
  end
  
  def setAudioCodingFlag(value)
    @audioCodingFlag = value
  end
  
  def getAudioCodingFlag
    @audioCodingFlag 
  end
  
  def setNumChannelsFlag(value)
    @numChannelsFlag = value
  end
  
  def getNumChannelsFlag
    @numChannelsFlag 
  end
  
  def setMixTypeFlag(value)
    @mixTypeFlag = value
  end
  
  def getMixTypeFlag
    @mixTypeFlag 
  end
  
  def setAudioLanguageFlag(value)
    @audioLanguageFlag = value
  end
  
  def getAudioLanguageFlag
    @audioLanguageFlag 
  end
  
end

